package cn.pxs.controller;


import cn.pxs.entity.Book;
import cn.pxs.entity.LargeFile;
import cn.pxs.entity.NewBook;
import cn.pxs.service.BookService;
import cn.pxs.service.LargeFileService;
import cn.pxs.tool.RespJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@RequestMapping("/api/adm/book")
@Controller
public class BookController {
    @Autowired
    private BookService bookService;
    @Autowired
    private LargeFileService largeFileService;

    @ResponseBody
    @RequestMapping("/findAll")
    public Map findAll(){
        int n = 200;
        List<NewBook> books = bookService.findAll();
        return RespJson.pack(n,"成功了",books);
    }

    @ResponseBody
    @RequestMapping("/findById/{id}")
    //绑定地址栏 id
    public Map findById(@PathVariable("id") Integer id){
        int n = 200;
        NewBook book = bookService.findById(id);
        return RespJson.pack(n,"成功了",book);
    }

    @ResponseBody
    @RequestMapping("findByPage/{start}/{num}")
    //绑定地址栏 start 和 num
    public Map findByPage(@PathVariable("start")Integer start,
                          @PathVariable("num")Integer num){
//        if(start<=0) return RespJson.pack(100,"失败了",null);
        Map map = new HashMap();
        map.put("total",bookService.findByLine());
        map.put("books",bookService.findByPage(start, num));
        return RespJson.pack(200,"成功了",map);
    }

    @ResponseBody
    @PostMapping("/addBook")
    //绑定参数pic  获取文件/图片
    public Map updateOrAdd(@RequestParam(value = "pic",required = false)MultipartFile file,
                   NewBook newBook, LargeFile largeFile) {
        NewBook book = bookService.updateOrAdd(file,largeFile, newBook);//修改
        return RespJson.pack(200,"成功",book);
    }

    @RequestMapping(value = "/show/{id}",produces =MediaType.IMAGE_GIF_VALUE)
    @ResponseBody
    //显示 图片 MediaType.IMAGE_GIF_VALUE返回类型 为img
    //绑定了地址栏id
    public byte[] show(@PathVariable("id")String id){
        LargeFile largeFile = largeFileService.findById(id);//根据id找该图片
        Object o = largeFile.getContent();
        byte[] buf =(byte[])o;//用byte[]输出
        return buf;
    }
}
